<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button v-permission="['POST /admin/brand/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="index" align="center" label="序号" width="50" />

      <el-table-column align="center" label="配方名称" prop="name" />

      <el-table-column align="center" label="原料详情" prop="materialName" />

      <el-table-column align="center" label="温度范围" prop="tempAttrName" />

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/brand/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/brand/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="80px" style="width: 500px; margin-left:50px;">

        <el-form-item label="配方名称" prop="name">
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item label="原料">
          <el-select v-model="dataForm.materialId" clearable>
            <el-option v-for="item in materialList" :key="item.value" :label="item.text" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item v-for="(item,index) in attrName" :key="index" :label="item.text" prop="materialId">
          <el-card class="box-card">
            <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="handleTempShow(item.name)" />
            <el-table :data="attr[item.name]">
              <el-table-column property="unitName" label="量度名称" />
              <el-table-column property="value" label="重量(g)" />
              <el-table-column property="devParam" label="机器参数" />
              <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" circle size="mini" style="width:auto;padding:5px" @click="handleTempEdit(scope.row)" />
                  <el-button type="danger" icon="el-icon-delete" circle size="mini" style="width:auto;padding:5px" @click="handleTempDelete(scope.row)" />
                </template>
              </el-table-column>
            </el-table>

          </el-card>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="addTempShow" title="新增配方属性">
      <el-form
        ref="addTempForm"
        :model="addTempForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="code" prop="code" style="display:none">
          <el-input v-model="addTempForm.code" />
        </el-form-item>
        <el-form-item label="量度名称" prop="unitName">
          <el-input v-model="addTempForm.unitName" />
        </el-form-item>
        <el-form-item label="重量(g)" prop="value">
          <el-input v-model="addTempForm.value" />
        </el-form-item>
        <el-form-item label="机器参数" prop="devParam">
          <el-input v-model="addTempForm.devParam" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addTempShow = false">取消</el-button>
        <el-button v-if="attrStatus=='create'" type="primary" @click="handleTempAttrAdd">确定</el-button>
        <el-button v-else type="primary" @click="handleTempAttrEdit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import { listFormula, insertFormula, editFormula, detailFormula, deleteFormula, insertFormulaAttr, updateFormulaAttr, deleteFormulaAttr, allMaterial } from '@/api/goods'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Material',
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: 'add_time',
        order: 'desc'
      },
      // 配方温度
      addTempShow: false,
      attrName: [{
        name: 'temp',
        text: '温度'
      }, {
        name: 'sweet',
        text: '甜度'
      }, {
        name: 'dense',
        text: '浓度'
      }],
      attr: {
        temp: [],
        sweet: [],
        dense: []
      },
      addTempForm: {
        'code': '',
        'unitName': '',
        'value': '',
        'devParam': ''
      },
      // 原料
      materialList: [],
      dataForm: {
      },
      dialogFormVisible: false,
      dialogStatus: '',
      attrStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        materialId: [
          { required: true, message: '原料不能为空', trigger: 'blur' }
        ],
        unitName: [
          { required: true, message: '量度名称不能为空', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '重量不能为空', trigger: 'blur' }
        ],
        devParam: [
          { required: true, message: '机器参数不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  computed: {
    headers() {
      return {
        'x-yipao-admin-token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listFormula(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    getMaterial: function() {
      allMaterial().then(response => {
        this.materialList = response.data.data.list
      })
    },
    // 添加温度属性
    handleTempAttrAdd() {
      this.$refs['addTempForm'].validate(valid => {
        if (valid) {
          insertFormulaAttr(this.addTempForm)
            .then(response => {
              console.log(this.addTempForm)
              this.attr[this.addTempForm.code].unshift(response.data.data)
              this.addTempShow = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 编辑温度属性
    handleTempAttrEdit() {
      this.$refs['addTempForm'].validate(valid => {
        if (valid) {
          updateFormulaAttr(this.addTempForm)
            .then(response => {
              console.log(this.addTempForm)
              // this.attr[this.addTempForm.code].unshift(response.data.data)
              this.addTempShow = false
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleTempDelete(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFormulaAttr(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.attr.indexOf(row)
            this.attr.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    // 新增属性
    handleTempShow(name) {
      this.attrStatus = 'create'
      this.addTempForm = { code: name }
      this.addTempShow = true
    },
    // 编辑属性
    handleTempEdit(row) {
      this.attrStatus = 'update'
      this.addTempForm = row
      this.addTempShow = true
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        name: '',
        materialId: '',
        tempAttrId: '',
        sweetAttrId: '',
        denseAttrId: ''
      }
      this.attr = {
        temp: [],
        sweet: [],
        dense: []
      }
    },
    // 新增配方-打开页面
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 原料
      this.getMaterial()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    uploadPicUrl: function(response) {
      this.dataForm.picUrl = response.data.url
    },
    // 新增配方
    createData() {
      this.dataForm.tempAttrId = Array.from(this.attr.temp, (v) => v.id).toString()
      this.dataForm.sweetAttrId = Array.from(this.attr.sweet, (v) => v.id).toString()
      this.dataForm.denseAttrId = Array.from(this.attr.dense, (v) => v.id).toString()
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          insertFormula(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
              this.getList()
            })
            .catch(response => {
              console.log('response')
              console.log(response)
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 编辑配方、显示详情--打开页面
    handleUpdate(row) {
      // this.dataForm = Object.assign({}, row)
      console.log('编辑配方、显示详情')
      detailFormula(row)
        .then((res) => {
          console.log('res')
          console.log(res)
          this.dataForm = res.data
          this.attr.temp = res.data.attr.temp || []
          this.attr.sweet = res.data.attr.sweet || []
          this.attr.dense = res.data.attr.dense || []
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
      // 原料
      this.getMaterial()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新配方
    updateData() {
      this.dataForm.tempAttrId = Array.from(this.attr.temp, (v) => v.id).toString()
      this.dataForm.sweetAttrId = Array.from(this.attr.sweet, (v) => v.id).toString()
      this.dataForm.denseAttrId = Array.from(this.attr.dense, (v) => v.id).toString()
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          editFormula(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
              this.getList()
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteFormula(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '品牌商ID',
          '品牌商名称',
          '介绍',
          '低价',
          '品牌商图片'
        ]
        const filterVal = ['id', 'name', 'desc', 'floorPrice', 'picUrl']
        excel.export_json_to_excel2(
          tHeader,
          this.list,
          filterVal,
          '品牌商信息'
        )
        this.downloadLoading = false
      })
    }
  }
}
</script>
